//
//  LLNWHTTPConnection.m
//  LLFoundation
//
//  Created by my_liu on 2016/11/14.
//  Copyright © 2016年 . All rights reserved.
//

#import "LLNWHTTPConnection.h"
#import "LLNWHTTPFileHandler.h"
#import "LLNWRequestManager.h"
#import <netinet/in.h>

@interface LLNWHTTPConnection ()

@property (nonatomic,strong) LLNWRequestManager *AFManager;

@end

@implementation LLNWHTTPConnection

- (id)init
{
    self = [super init];
    
    if (self)
    {
        self.AFManager = [LLNWRequestManager manager];
    }
    return self;
}

+ (id)shareInstance
{
    static LLNWHTTPConnection *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[LLNWHTTPConnection alloc] init];
    });
    return instance;
}

- (BOOL)checkNetworkConnection
{
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL,(struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability,&flags);
    CFRelease(defaultRouteReachability);
    if (didRetrieveFlags) {
        BOOL isReachable = flags & kSCNetworkFlagsReachable;
        BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
        return (isReachable && !needsConnection) ? YES : NO;
    } else {
        return NO;
    }
}

- (void)cancelRequestWithRequestKey:(NSString *)requestKey
{
    [self.AFManager cancelRequestWithRequestKey:requestKey];
}

#pragma mark -
#pragma mark POST、GET

- (void)requestSource:(id)manager withInfo:(LLNWHTTPDetails *)requestInfo success:(void(^)(LLNWHTTPResponse *response))success failure:(void(^)(LLNWHTTPResponse *response))failure
{
    [self.AFManager start:manager withInfo:requestInfo success:success failure:failure];
}

@end
